package com.cwf.security.service.impl;

import com.alibaba.fastjson2.JSON;
import com.cwf.security.dao.PermissionListDao;
import com.cwf.security.entity.Permission;
import com.cwf.security.service.RedisPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RedisPermissionServiceImpl implements RedisPermissionService {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Autowired
    PermissionListDao permissionListDao;


    @Override
    public List<String> getPermission(String uid) {

//        String key = "permission:" + uid;
//
//        List<String> list = new ArrayList<>();
//        try {
//            Object cacheList = redisTemplate.opsForValue().get(key);
//            JSON.toJSONString(cacheList);
//            list = JSON.parseArray(JSON.toJSONString(cacheList),String.class);
//        }catch (Exception e){
//            log.warn("\n获取{}缓存异常",key);
//            log.info("\n开始重新设置缓存");
//        }
//
//        if (list!=null){
//            return list;
//        }
        return this.setRedisPermission(uid);
    }


    @Override
    public List<String> setRedisPermission(String uid) {
        String key = "permission:" + uid;

        List<Permission> list = permissionListDao.accessList(uid);

        List<String> collect = list.stream()
                .filter(v -> v.getCategory() == 3)
                .map(Permission::getMark)
                .collect(Collectors.toList());

        if (list.size()!=0){
            redisTemplate.opsForValue().set(key,collect);
            log.info("\n设置{}缓存成功!",key);
            System.out.println(collect);
        }
        return collect;

    }
}
